package com.hjy;

import java.util.Arrays;

/**
 * 数组的自定义功能实现
 * 使用 <E> 标识泛型
 */
public class Array<T> {
    private T[] data;
    private int size;

    public Array() {
        this(10);//默认数组长度为10
    }
    public Array(int capactiy){
        data = (T[]) new Object[capactiy];
    }

    public int getCapactiy(){
        return data.length;
    }

    public int getSize(){
        return size;
    }

    public boolean isEmpty(){
        return size==0;
    }

    public void add(int index,T e){
        if(size == data.length){
            throw new RuntimeException("array is full ,add failed");
        }

        if(index <0 || index > size){
            throw new RuntimeException("add failed, requeied index >=0 and index <=size");
        }
        //指定位置添加，如要将后面的往后移
        for (int i = size -1; i >= index ; i--) {
            data[i+1] = data[i];
        }
        data[index] =  e;
        size++;
    }
    public void addFirst(T e){
        add(0, e);
    }
    public void addLast(T e){
        add(size, e);
    }

    public T get(int index){
        if(index <=0 || index > size){
            throw new RuntimeException("get failed ,require index >=0 and index <=size");
        }
        return data[index];
    }

    public void  set(int index, T e){
        add(index, e);
    }

    public boolean find(T e){
        for (int i = 0; i < size ; i++) {
            if(data[i] == e) return true;
        }
        return false;
    }

    public boolean contains(T e){
        return find(e);
    }

    //删除袁术需要将数据元素删除，同时返回删除元素
    public T del(int index){
        if(index <=0 || index > size){
            throw new RuntimeException("get failed ,require index >=0 and index <=size");
        }
        T ret = data[index];
        for (int i = index+1; i < size ; i++) {
            data[i-1] = data[i];
        }
        //当前大小减去1
        size--;
        return ret;
    }

    private void resize(int newcaptiy){
        data = (T[]) new Object[newcaptiy];
    }

    //删除第一个元素，返回第一个元素
    public T delFirst(){
        return del(0);
    }
    //删除最后一个元素
    public T delLast(){
        return del(size-1);
    }

    public T getLast(){
        return get(size-1);
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("Array: size = %d, capactiy = %d \n", size, data.length));
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(data[i]);
            if(i != size - 1){
                sb.append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
